<template>
    <div>

        <AddSubchanceDialog :visible="addSubchanceDialogVisible" :close="closeAddSubchance" :callback="addSubchance" :options="options"></AddSubchanceDialog>
        <AddCompetitionDialog :visible="addCompetitionDialogVisible" :close="closeAddCompetition" :callback="addCompetition" :options="options"></AddCompetitionDialog>
        <AddPurchaseDialog :visible="addPurchaseDialogVisible" :close="closeAddPurchase" :callback="addPurchase" :options="options"></AddPurchaseDialog>

        <el-dialog :visible.sync="visible" :before-close="handleCloseAddChance" @close="confirmCloseAddChance"
                   :fullscreen="fullscreen" width="90%" top="4vh">


            <div slot="title">
                <div
                    style=" width:830px;display: flex;align-items: center;justify-content: space-between;border-bottom: #99a9bf 1px solid;padding-bottom: 10px">
                    <span style="font-weight: bold">Add Chance</span>
                    <div>

                        <el-button type="primary" icon="el-icon-edit-outline" @click="handleTemporalStore"> Temporal Store
                        </el-button>

                        <el-button type="primary" icon="el-icon-upload" @click="handleUpload">Upload
                        </el-button>

                        <el-button icon="el-icon-refresh-left" @click="handleCancelAddChance">
                            Cancel
                        </el-button>

                    </div>
                </div>

            </div>
            <div class="fullscreen" @click="onFullScreenClick">
                <i class="el-icon-full-screen"/>
            </div>

            <el-row :gutter="20">
                <el-col :span="12">

                    <el-card shadow="never" class="box-card">
                        <div slot="header" class="clearfix">
                            <span style="font-weight:bold">Chance Info</span>

                        </div>
                        <el-form ref="elForm-addChance" :model="addChanceForm" :rules="addChanceRules" size="medium"
                                 label-width="100px"
                                 label-position="left">
                            <el-row type="flex" justify="start" align="top">

                                <el-form-item label="chanceId" label-width="80px" prop="chanceId">
                                    <el-input v-model="addChanceForm.chanceId" clearable :disabled="true"
                                              :style="{width: '100%'}">
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="chanceName" label-width="140px" prop="chanceName">
                                    <el-input v-model="addChanceForm.chanceName" placeholder="Please Enter" clearable
                                              :style="{width: '100%'}">
                                    </el-input>
                                </el-form-item>

                                <el-form-item label="customerName" label-width="140px" prop="customerName">
                                    <el-select v-model="addChanceForm.customerName" placeholder="Please Enter" filterable clearable
                                               :style="{width: '100%'}">
                                        <el-option v-for="(item, index) in options.customerNameOptions" :key="index" :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>

                            </el-row>
                            <el-row type="flex" justify="start" align="top">
                                <el-form-item label="chanceResource" label-width="140px" prop="chanceResource">
                                    <el-select v-model="addChanceForm.chanceResource" placeholder="Please Enter" filterable clearable
                                               :style="{width: '100%'}">
                                        <el-option v-for="(item, index) in options.chanceResourceOptions" :key="index" :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="chancePhase" label-width="140px" prop="chancePhase">
                                    <el-select v-model="addChanceForm.chancePhase" placeholder="Please Choose" filterable clearable
                                               :style="{width: '100%'}">
                                        <el-option v-for="(item, index) in options.chancePhaseOptions" :key="index" :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>

                            </el-row>
                            <el-row type="flex" justify="start" align="top">
                                <el-form-item label="chanceBelong" label-width="140px" prop="chanceBelong">
                                    <el-select v-model="addChanceForm.chanceBelong" placeholder="Please Choose" filterable clearable
                                               :style="{width: '100%'}">
                                        <el-option v-for="(item, index) in options.chanceBelongOptions" :key="index" :label="item.label"
                                                   :value="item.value" :disabled="item.disabled"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label-width="140px" label="oldCustomer" prop="chanceOldCustomer">
                                    <el-switch v-model="addChanceForm.chanceOldCustomer"
                                               active-value="YES"
                                               inactive-value="NO"></el-switch>
                                </el-form-item>
                                <el-form-item label="chanceTime" label-width="140px" prop="chanceTime">
                                    <el-date-picker v-model="addChanceForm.chanceTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                                    :style="{width: '100%'}" placeholder="Y-M-D" clearable></el-date-picker>
                                </el-form-item>
                            </el-row>
                            <el-form-item label-width="120px" label="background" prop="chanceBackground">
                                <el-input v-model="addChanceForm.chanceBackground" type="textarea" placeholder="Please Enter"
                                          :autosize="{minRows: 2, maxRows: 5}" :style="{width: '100%'}"></el-input>
                            </el-form-item>
                        </el-form>
                    </el-card>

                    <el-card shadow="never" class="box-card">
                        <div slot="header" class="clearfix">
                            <span style="font-weight:bold">Subchance Table</span>
                            <el-button type="primary" icon="el-icon-plus" @click="openAddSubchanceDialog" style="float: right">Add
                            </el-button>
                        </div>

                        <el-table
                            :header-cell-style="{fontSize:'12px',background:'#eef1f6',color:'#495085'}"
                            v-loading="this.$store.getters.isLoading" :data="subchanceTable" show-summary>
                            <el-table-column
                                type="index"
                                width="80"
                                label="Index">
                            </el-table-column>
                            <el-table-column property="subchanceName" label="name"></el-table-column>
                            <el-table-column property="subchanceType" label="type"></el-table-column>
                            <el-table-column property="subchanceProduct" label="product"></el-table-column>
                            <el-table-column property="subchanceDept" label="dept"></el-table-column>
                            <el-table-column property="subchanceMoney" label="money"></el-table-column>
                            <el-table-column label="Operate">
                                <template slot-scope="scope">

                                    <el-button
                                        size="mini"
                                        type="danger"
                                        @click="handleDeleteSubChance(scope.$index, scope.row)">Delete
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>


                    </el-card>

                </el-col>


                <el-col :span="12">

                    <el-card shadow="never" class="box-card">
                        <div slot="header" class="clearfix">
                            <span style="font-weight:bold">Approval flow chart</span>
                        </div>
                        <div>
                            <el-steps :space="300" :active="parseInt(addChanceForm.chanceStatus)" align-center>
                                <el-step title="Submitter"></el-step>
                                <el-step title="vice president of marketing"></el-step>
                                <el-step title="Sales Director/General Manager of Business"></el-step>
                            </el-steps>
                        </div>

                    </el-card>

                    <el-card shadow="never" class="box-card">
                        <div slot="header" class="clearfix">
                            <span style="font-weight:bold"> Competition </span>

                            <el-button type="primary" icon="el-icon-plus" @click="openAddCompetitionDialog" style="float: right">New
                            </el-button>

                        </div>

                        <el-table :data="competitionTable"      :header-cell-style="{fontSize:'12px',background:'#eef1f6',color:'#495085'}">
                            <el-table-column
                                type="index"
                                width="80"
                                label="Index">
                            </el-table-column>
                            <el-table-column property="competitionRival" label="Rival"></el-table-column>
                            <el-table-column property="competitionPotential" label="Potential"></el-table-column>

                            <el-table-column label="Operate">
                                <template slot-scope="scope">

                                    <el-button
                                        size="mini"
                                        type="danger"
                                        @click="handleDeleteCompetition(scope.$index, scope.row)">Delete
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>

                    <el-card shadow="never" class="box-card"      :header-cell-style="{fontSize:'12px',background:'#eef1f6',color:'#495085'}">
                        <div slot="header" class="clearfix">
                            <span style="font-weight:bold"> Purchase </span>

                            <el-button type="primary" icon="el-icon-plus" @click="handleAddPurchase" style="float: right">New
                            </el-button>

                        </div>

                        <el-table :data="purchaseTable">

                            <el-table-column property="purchaseName" label="name"></el-table-column>
                            <el-table-column property="purchaseDept" label="dept"></el-table-column>
                            <el-table-column property="purchasePosition" label="position"></el-table-column>
                            <el-table-column property="purchasePhone" label="phone"></el-table-column>
                            <el-table-column property="purchaseDecision" label="decision"></el-table-column>
                            <el-table-column property="purchaseEffect" label="effect"></el-table-column>
                            <el-table-column property="purchaseAccept" label="accept"></el-table-column>

                            <el-table-column label="Operate">
                                <template slot-scope="scope">

                                    <el-button
                                        size="mini"
                                        type="danger"
                                        @click="handleDeletePurchase(scope.$index, scope.row)">Delete
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                </el-col>
            </el-row>
        </el-dialog>


    </div>
</template>

<script>
import AddSubchanceDialog from "./InnerDialog/AddSubchanceDialog";
import AddCompetitionDialog from "./InnerDialog/AddCompetitionDialog";
import AddPurchaseDialog from "./InnerDialog/AddPurchaseDialog";

export default {
    name: "AddChanceDialog",
    components: {AddPurchaseDialog, AddCompetitionDialog, AddSubchanceDialog},
    props: ['visible', 'options','close','callback'],
    data() {
        return {

            fullscreen: false,

            //sub-dialog-visible
            addSubchanceDialogVisible: false,
            addCompetitionDialogVisible: false,
            addPurchaseDialogVisible: false,

            //新增机会的对话框表单

            addChanceForm:      {
                "chanceId": null,
                "chanceCode": null,
                "chanceName": null,
                "chanceResource": null,
                "chancePhase": null,
                "chanceBelong": null,
                "chanceStatus": null,
                "chanceType": null,
                "chanceOldCustomer": "NO",
                "customerName": null,
                "customerMgrName": null,
                "customerMgrDept": null,
                "chanceTime": null,
                "chanceBackground": null
            },

            addChanceRules: {
                chanceName: [{
                    required: true,
                    message: 'Please Enter',
                    trigger: 'blur'
                }],
                customerName: [{
                    required: true,
                    message: 'Please Enter',
                    trigger: 'blur'
                }],
                chanceResource: [{
                    required: true,
                    message: 'Please Enter',
                    trigger: 'change'
                }],
                chancePhase: [{
                    required: true,
                    message: 'Please Enter',
                    trigger: 'change'
                }],
                chanceBelong: [{
                    required: true,
                    message: 'Please Enter',
                    trigger: 'change'
                }],
                chanceTime: [{
                    required: true,
                    message: 'Please Enter',
                    trigger: 'change'
                }],
                chanceBackground: [{
                    required: true,
                    message: 'Please Enter',
                    trigger: 'blur'
                }],
            },
            newApproval: {
                approvalId:null,
                approvalName: null,
                approvalMember: null,
                approvalStatus: null,
                approvalAdvice: null,
                approvalTime: null,

                approvalHandleAdvice: null,
                approvalUploader: null,
                approvalUptime: null,
            },

            subchanceTable: [],

            competitionTable: [],

            purchaseTable: [],

        }
    },

    methods: {

        //获取所有的客户名字和编号，用于创建add chance
        init(nextId){
            this.$axios.post(
                '/customer/customer/queryAllCustomer',

            ).then(res => {
                // console.log(res.data.obj);

                this.options.customerNameOptions=[];

                for(var i=0;i<res.data.obj.length;i++){
                    var item={ "label": "",
                        "value": ""}
                    item.label=res.data.obj[i].customerName
                    item.value=res.data.obj[i].customerId
                    this.options.customerNameOptions.push(item)
                }
                console.log(this.options.customerNameOptions)
            });

            this.addChanceForm.chanceId = nextId
        },

        //全屏
        onFullScreenClick() {
            this.fullscreen = !this.fullscreen
        },
        handleTemporalStore(){
            this.addChanceForm.chanceStatus = 'Draft'
            this.handleConfirmAddChance();
        },
        handleUpload(){
            this.addChanceForm.chanceStatus = 'Under Process'
            this.handleConfirmAddChance();
        },
        //新增机会确定
        handleConfirmAddChance() {
            console.log("add chance");
            let chanceId
            this.$refs['elForm-addChance'].validate(valid => {
                if (!valid) return
                // var this = this
                const tthis = this
                console.log("Now the Chance table is")
                console.log(this.addChanceForm)
                this.$axios.post(
                    '/chance/chance/addChance',
                    this.addChanceForm
                ).then(res => {
                     chanceId = res.data.obj
                    // 添加子机会
                    for(var subchance in tthis.subchanceTable){
                        let subchanceAdd = {
                            "chanceId" : chanceId,
                            "subchance" : tthis.subchanceTable[subchance]
                        }
                        console.log("Now the subchance table is")
                        console.log(subchanceAdd)
                        tthis.$axios.post("/chance/chance/addSubchance", subchanceAdd).then(e => {
                            console.log(e)
                        })
                    }
                    // 添加购买
                    for(var purchase in tthis.purchaseTable){
                        let purchaseAdd = {
                            "chanceId" : chanceId,
                            "purchase" : tthis.purchaseTable[purchase]
                        }
                        console.log("Now the purchase table is")
                        console.log(purchaseAdd)
                        tthis.$axios.post("/chance/chance/addPurchase", purchaseAdd).then(e => {
                            console.log(e)
                        })
                    }
                    // 添加竞争
                    for(var competition in tthis.competitionTable){
                        let competitionAdd = {
                            "chanceId" : chanceId,
                            "competition" : tthis.competitionTable[competition]
                        }
                        console.log("Now the competition table is")
                        console.log(competitionAdd)
                        tthis.$axios.post("/chance/chance/addCompetition", competitionAdd).then(e => {
                            console.log(e)
                        })
                    }

                    // 添加审批
                    this.newApproval.approvalStatus = 'Waiting For Approval'
                    this.newApproval.approvalAdvice = 'Modify after returned'
                    let dto = {
                        chanceId: chanceId,
                        role: this.$npms.roles.CUSTOMER_MGR,
                        approval: this.newApproval,
                    }
                    this.$axios.post("/approve/approve/addChanceApproval", dto)
                    //深拷贝
                    const dd = JSON.parse(JSON.stringify(this.addChanceForm))
                    this.callback(dd);
                    this.$message.success(res.data.msg)
                    this.subchanceTable = []
                    this.purchaseTable = []
                    this.competitionTable = []
                });
                console.log('before close', this.addChanceForm);
                this.confirmCloseAddChance();
            })
        },

        //新增机会取消
        handleCancelAddChance() {
            console.log("cancel chance");
            this.$refs['elForm-addChance'].resetFields();
            this.close();
        },

        //新增机会弹窗关闭的确认框
        handleCloseAddChance(done) {
            this.$confirm('Closing now will lose all unsaved data. Confirm closing?',{cancelButtonText:'cancel',confirmButtonText:'confirm'})
                // eslint-disable-next-line no-unused-vars
                .then(e => {
                    done();
                })
        },

        //关闭新增机会弹窗
        confirmCloseAddChance() {
            console.log("close the dialog");

            this.$refs['elForm-addChance'].resetFields();

            this.close();
        },


        //新增子机会弹窗
        openAddSubchanceDialog() {
            console.log("open Add Subchance Dialog");
            this.addSubchanceDialogVisible = true
        },

        //删除子机会
        handleDeleteSubChance(index, row) {
            console.log(index, row);


            this.$confirm('Are you sure you want to delete the sub-opportunity?','WARN', {
                confirmButtonText: 'Confirm',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {
                console.log(index, row);

                this.subchanceTable.splice(index, 1)
                this.$message({
                    type: 'success',
                    message: 'Delete Successful!'
                });
            })

        },

        //关闭子机会弹窗
        closeAddSubchance() {
            this.addSubchanceDialogVisible = false
        },

        //添加子机会点击后回调函数
        addSubchance(subchance) {

            this.subchanceTable.push(subchance)
            console.log(subchance)
        },

        //新增竞争情况弹窗
        openAddCompetitionDialog() {
            console.log("open Add Competition Dialog");
            this.addCompetitionDialogVisible = true
        },

        //删除情况竞争
        handleDeleteCompetition(index, row) {
            console.log(index, row);

            this.$confirm('Are you sure you want to remove the situation competition?', 'WARN', {
                confirmButtonText: 'Confirm',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {
                console.log(index, row);

                this.competitionTable.splice(index, 1)
                this.$message({
                    type: 'success',
                    message: 'Delete Successful!'
                });
            })
        },

        //关闭新增竞争情况弹窗
        closeAddCompetition() {
            this.addCompetitionDialogVisible = false
        },


        //添加竞争点击后回调函数
        addCompetition(competition) {

            this.competitionTable.push(competition)
            console.log(competition)
        },

        //新增购买决策人
        handleAddPurchase() {
            console.log("Add Purchase");
            this.addPurchaseDialogVisible = true
        },

        //删除购买决策人
        handleDeletePurchase(index, row) {
            console.log(index, row);

            this.$confirm('Are you sure you want to delete the purchase decision maker?', 'WARN', {
                confirmButtonText: 'Confirm',
                cancelButtonText: 'Cancel',
                type: 'warning'
            }).then(() => {
                console.log(index, row);

                this.purchaseTable.splice(index, 1)
                this.$message({
                    type: 'success',
                    message: 'Delete Successful!'
                });
            })
        },

        //关闭购买决策人弹窗
        closeAddPurchase() {
            this.addPurchaseDialogVisible = false
        },

        //添加竞争点击后回调函数
        addPurchase(purchase) {

            this.purchaseTable.push(purchase)
            console.log(purchase)
        },

    }

}
</script>


<style scoped>

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.box-card {
margin-top: 10px;
}

.fullscreen {
    position: absolute;
    right: 50px;
    top: 18px;
    cursor: pointer;
    transition: all 200ms;
}

.fullscreen:hover {
    color: #6DBEF8;
}
</style>